#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLESPrerequisites.h"
#include "OgreGLESRenderSystem.h"

#include "OgreSymbianEGLSupport.h"
#include "OgreSymbianEGLWindow.h"
#include "OgreSymbianEGLRenderTexture.h"
#include "OgreSymbianEGLContext.h"

#include <e32base.h>
#include <coemain.h>

namespace Ogre
{
	SymbianEGLSupport::SymbianEGLSupport()
	{
		TSizeMode sizeMode = CCoeEnv::Static()->ScreenDevice()->GetCurrentScreenModeAttributes();
		
		mCurrentMode.first.first = sizeMode.iScreenSize.iWidth;
		mCurrentMode.first.second = sizeMode.iScreenSize.iHeight;
		mCurrentMode.second = 0;
		mOriginalMode = mCurrentMode;
		mVideoModes.push_back(mCurrentMode);
		
		mNativeDisplay = EGL_DEFAULT_DISPLAY;
		mGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
		if (mGLDisplay != NULL)
		{
			if (eglInitialize(mGLDisplay, NULL, NULL) == EGL_FALSE)
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
							"EGL Initialize failed!",
							"SymbianEGLSupport::SymbianEGLSupport");
			}
		}
	}
	
	SymbianEGLSupport::~SymbianEGLSupport()
	{
		
	}
	
	EGLWindow* SymbianEGLSupport::createEGLWindow(EGLSupport* support)
	{
		return new SymbianEGLWindow(support);
	}
	
	GLESPBuffer* SymbianEGLSupport::createPBuffer(PixelComponentType format, size_t width, size_t height)
	{
		return new SymbianEGLPBuffer(this, format, width, height);
	}
	
	void SymbianEGLSupport::switchMode(uint& width, uint& height, short& frequency)
	{
		if (!mRandr)
			return;
			
		int size = 0;
		int newSize = -1;
		
		VideoModes::iterator mode;
		VideoModes::iterator end = mVideoModes.end();
		VideoMode *newMode = 0;
		
		for (mode = mVideoModes.begin(); mode != end; size++)
		{
			if (mode->first.first >= static_cast<int>(width) &&
				mode->first.second >= static_cast<int>(height))
			{
				if (!newMode ||
					mode->first.first < newMode->first.first ||
					mode->first.second < newMode->first.second)
				{
					newSize = size;
					newMode = &(*mode);
				}
			}
			
			while(++mode != end && mode->first == lastMode->first)
			{
				if (lastMode == newMode && mode->second == frequency)
				{
					newMode = &(*mode);
				}
			}
		}
	}
	
	RenderWindow* SymbianEGLSupport::newWindow(const String& name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList* miscParams)
	{
		SymbianEGLWindow* window = new SymbianEGLWindow(this);
		window->create(name, width, height, fullScreen, miscParams);
		
		return window;
	}
}
